define(function () {
    'use strict';

    //b=0 三方存管重新绑定 b=1 新开户绑定三方存管  无b 补开三方存管
    function ctrl($scope,$state,$sce,$stateParams,$ionicLoading,$ionicModal,$q,CommonService,WebService,LocalCacheService) {

        var par = $scope.param = {};
        par.step= 1;

        $scope.$on('$ionicView.beforeEnter', function() {
            par.step= 1;
            par.b = $stateParams["b"];
            $scope.deposit_banks = new Array();
            par.bank_name='请选择银行';
            par.agreement=true;
            par.bind_success = false;
            if(LocalCacheService.get("BindDepositBankCtrl_bankInfo")){
                var bankInfo = LocalCacheService.get("BindDepositBankCtrl_bankInfo");
                par.bank_name = bankInfo.bank_name;
                par.contract_way = bankInfo.contract_way;
                par.ispwd = bankInfo.ispwd;
                par.brief = bankInfo.brief;
                par.econtract_id = bankInfo.econtract_id;
                par.bank_no = bankInfo.bank_no;
                par.bank_account = bankInfo.bank_account;
                par.bank_pwd = bankInfo.bank_pwd;
                LocalCacheService.remove("BindDepositBankCtrl_bankInfo");
            }

            init();
        });

        function init(){
            //查询所有存管银行
            WebService.qryAllDepositBank().then(
                function(data){
                    for(var i=0; i < data.length; i++){
                        var deposit_bank = data[i];
                        deposit_bank.brief = $sce.trustAsHtml(deposit_bank.brief);
                        $scope.deposit_banks.push(deposit_bank);
                    }
                }
            );
            //重绑存管
            if(!CommonService.isStrEmpty(par.b) && "0" == par.b){
                par.step = 2;
                WebService.qryOpenResult().then(
                    function(data){
                        par.fail_info = "存管绑定处理失败，失败原因：" + data.open_result + "</br>请重新绑定";
                    }
                );
            }

            createModel();
        }

        function createModel(){
            var deferred = $q.defer();
            if(!$scope.bank_modal) {
                $ionicModal.fromTemplateUrl("open/depositBankList.html", {
                    scope: $scope,
                    animation: "slide-in-up"
                }).then(function(modal) {
                    $scope.bank_modal = modal;
                    deferred.resolve();
                });
            } else {
                deferred.resolve();
            }
            return deferred.promise;
        }

        $scope.$on("$destroy", function() {
            $scope.bank_modal.remove();
        });

        $scope.closeModal = function() {
            $scope.bank_modal.hide();
        };

        $scope.showBankClick = function(){
            $scope.bank_modal.show();
        };

        $scope.selectBank = function(bank){
            if("5" == bank.bank_no) { //中国银行
                par.pwd_msg = '请输入电话银行密码';
            } else {
                par.pwd_msg = '请输入银行卡密码';
            }
            //contract_way 2 预指定 不需要卡号密码
            par.contract_way=bank.contract_way;
            //ispwd 一步式密码 1显示 2不显示 默认1
            par.ispwd=bank.ispwd;
            par.brief=bank.brief;
            par.bank_no=bank.bank_no;
            par.econtract_id=bank.econtract_id;
            par.bank_name=bank.bank_name;
            par.bank_account = null ;
            par.bank_pwd = null;
            $scope.bank_modal.hide();
        };

        $scope.saveBankInfo = function(){
            var bankInfo ={
                contract_way:par.contract_way,
                ispwd:par.ispwd,
                brief:par.brief.toString(),
                bank_no:par.bank_no,
                econtract_id:par.econtract_id,
                bank_name:par.bank_name,
                bank_account:par.bank_account,
                bank_pwd:par.bank_pwd
            };
            LocalCacheService.set("BindDepositBankCtrl_bankInfo", bankInfo);
        };


        $scope.bindBankClick = function(){
            if(checkMsg()){
                $ionicLoading.show();
                var params={bank_no:par.bank_no,bank_account:par.bank_account,econtract_id:par.econtract_id,source:CommonService.getSource()};
                if(par.need_pwd){
                    $.extend(params,{bk_password:par.bank_pwd});
                }
                //开户，绑定三方存管
                if(!CommonService.isStrEmpty(par.b)){
                    WebService.openBankAccount(params).then(
                        function(data){
                            bindSuccess();
                        },
                        function(error){
                            bindFail(error)
                        }
                    );
                }else{
                    //已开户，补开三方存管
                    WebService.reopenBankAccount(params).then(
                        function(data){
                            bindSuccess();
                        },
                        function(error){
                            bindFail(error)
                        }
                    );
                }
            }
        };

        function bindSuccess(){
            par.step= 2;
            $ionicLoading.hide();
            if(!CommonService.isStrEmpty(par.bank_account)){
                var bank_account = par.bank_account;
                par.bank_account_msg = '尾号<em>' + bank_account.substr(bank_account.length-4) + '</em>';
            }
            par.bind_success = true;
            if(!CommonService.isStrEmpty(par.b)){
                if("0"==par.b){
                    //三方存管重绑，直接跳转到开户结果页
                    $state.go("open-revisitPaper");
                }else{
                    //开户绑存管，跳转到签署协议
                    $state.go("open-signAgreement");
                }
            }
        }

        function bindFail(error){
            par.step= 2;
            $ionicLoading.hide();
            if("XCM-300001" == error.error_no) {//显示通知
                CommonService.showNotice(error.error_info);
            }else if("XCM-200011" == error.error_no){//下一交易日处理
                if(!CommonService.isStrEmpty(par.bank_account)){
                    var bank_account = par.bank_account;
                    par.bank_account_msg = '尾号<em>' + bank_account.substr(bank_account.length-4) +
                        '</em></br>我们会在1个交易日内完成您的资料审核，并在审核完成后短信通知您结果。成功后您就可以购买产品了。';
                }
                par.bind_success = true;
                if(!CommonService.isStrEmpty(par.b)){
                    if("0"==par.b){
                        //三方存管重绑，直接跳转到开户结果页
                        $state.go("open-revisitPaper");
                    }else{
                        //开户绑存管，跳转到签署协议
                        $state.go("open-signAgreement");
                    }
                }
            }else{
                par.fail_info = "失败原因：" + CommonService.getErrorInfo(error) + "</br>请重新绑定";
            }
        }

        $scope.reBind = function(){
            par.step= 1;
            par.bank_name='请选择银行';
            par.agreement=true;
            par.bind_success = false;
            par.bank_no='';
            par.bank_account='';
            par.contract_way='';
            par.ispwd='';
        };

        function checkMsg(){
            if(CommonService.isStrEmpty(par.bank_no)){
                CommonService.showAlert({message:"请选择银行"});
                return false;
            }
            if(par.contract_way != 2) {
                if(CommonService.isStrEmpty(par.bank_account)){
                    CommonService.showAlert({message:"请输入银行卡号"});
                    return false;
                }
                par.bank_account=CommonService.trim(par.bank_account);
                if(!/^\d{16,19}$/.test(par.bank_account)) {
                    CommonService.showAlert({message:"请输入正确银行卡号16-19位"});
                    return false;
                }
                if(par.ispwd == 1) {
                    if(CommonService.isStrEmpty(par.bank_pwd)) {
                        CommonService.showAlert({message: "请输入银行密码"});
                        return false;
                    }
                    if(!CommonService.checkRegex("^[0-9]{6}$",par.bank_pwd)) {
                        CommonService.showAlert({message: "银行密码格式不正确"});
                        return false;
                    }
                }
            }
            if(!par.agreement){
                CommonService.showAlert({message:"我已阅读并同意签署相关基金协议"});
                return false;
            }
            return true;
        }
    }

    ctrl.$inject = ['$scope','$state','$sce','$stateParams','$ionicLoading','$ionicModal','$q','CommonService','WebService','LocalCacheService'];
    return ctrl;
});